//
//  BRMessage.m
//  ZhuShou
//
//  Created by Dejun Liu on 15/11/9.
//  Copyright © 2015年 jw. All rights reserved.
//

#import "BRMessage.h"
#import "ByteBufferReader.h"
#import "ByteBufferWriter.h"

NSString *BRMessageNotificationDidFinishedProcessResponse = @"BRMessageNotificationDidFinishedProcessResponse";

@implementation BRMessage

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.timeOut = BRMessageDefaultTimeOut;
        self.maxRetryCount = BRMessageDefaultRetryCount;
        self.isFinished = NO;
    }
    return self;
}

- (void)setResponseMsg:(NSString *)responseMsg
{
    _responseMsg = responseMsg;
    _isFinished = YES;
}

+ (BRMessage *)messageWithCmd:(UInt16)cmd msg:(NSString *)msg
{
    BRMessage *obj = [[BRMessage alloc] init];
    obj.msg = msg;
    obj.cmd = cmd;
    return obj;
}

+ (BRMessage *)messageWithPackageData:(NSData *)data
{
    ByteBufferReader *reader = [[ByteBufferReader alloc] initWithData:data];
    reader.position = sizeof(UInt16)*0;
//    UInt16 packageLength = ntohs([reader readUInt16]);
    reader.position = sizeof(UInt16)*1;
    UInt16 cmd = ntohs([reader readUInt16]);
    reader.position = sizeof(UInt16)*2;
//    UInt16 msgLength = ntohs([reader readUInt16]);
    reader.position = sizeof(UInt16)*3;
    NSData *msgData = [reader readBytes:data.length-sizeof(UInt16)*3];
    NSString *msg = [msgData stringUTF8];
    
    BRMessage *msgObj = [[BRMessage alloc] init];
    msgObj.cmd = cmd;
    msgObj.msg = [msg copy];
    return msgObj;
}

- (NSData *)getPackageData
{
    NSData *mesData = [self.msg dataUTF8];
    
    ByteBufferWriter *byteBufWriter = [[ByteBufferWriter alloc] init];
    int allLength = mesData.length + 6;
    [byteBufWriter writeUInt16:htons(allLength)];
    int cmd = self.cmd;
    [byteBufWriter writeUInt16:htons(cmd)];
    int msgLength = mesData.length;
    [byteBufWriter writeUInt16:htons(msgLength)];
    [byteBufWriter writeBytes:mesData];
    
    return byteBufWriter.data;
}

- (void)callResponseBlockAtOtherThread
{
    [self performSelectorInBackground:@selector(callResponseBlock) withObject:nil];
}

- (void)callResponseBlock
{
    if (self.isFinished) {
        self.responseBlock(BRMessageResponseTypeSuccess,self.retryCount,self.responseMsg);
        //通知把消息队列中的消息移除掉，不让在重试了。
        [[NSNotificationCenter defaultCenter]postNotificationName:BRMessageNotificationDidFinishedProcessResponse object:self];
    }else
    {
        if (self.retryCount == self.maxRetryCount) {
            self.responseBlock(BRMessageResponseTypeTimeout,self.retryCount,self.responseMsg);
        }else
        {
            self.responseBlock(BRMessageResponseTypeRetrying,self.retryCount,self.responseMsg);
        }
    }
}

@end
